﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using AdHocReports.Properties;
using System.Net.Mail;
using System.Text;
using System.Diagnostics;
using System.Net;

namespace AdHocReports
{
    public class Global : System.Web.HttpApplication
    {
        public static bool Demo = false;
        public static bool Expired = false;
        public static int Days = 30;
        public static System.DateTime DateInstalled = System.DateTime.Now;
        private static int iMaxHistory = 50;
        private static bool bLogErrorDetails = false;
        private static bool bEncryptErrorLogEntries = true;
        private static FormHistory history = new FormHistory(iMaxHistory);

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            if (Session != null)
            {
                StringBuilder message = new StringBuilder();

                foreach (string key in Session.Keys)
                {
                    message.Append(Environment.NewLine);
                    message.AppendFormat("{0}: {1}", key, Session[key]);
                }

                Context.Items["ExceptionSessionKeys"] = message.ToString();
            }

            Server.Transfer("error.aspx");
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        //private static void HandleRegistration()
        //{
        //    //HandleRegistrationReg();
        //    string sPath = Server.MapPath(null);
        //    if (sPath.LastIndexOf("\\") != (sPath.Length - 1))
        //    {
        //        sPath += "\\";
        //    }
        //    System.IO.FileStream iofs = null;
        //    try
        //    {
        //        iofs = new System.IO.FileStream(sPath + "rt\\register.asax", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
        //    }
        //    catch (System.Exception ex1)
        //    {
        //        ex1.ToString();
        //        try
        //        {
        //            iofs = new System.IO.FileStream(sPath + "rt\\register.asax", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read);
        //        }
        //        catch (System.Exception ex2)
        //        {
        //            ex2.ToString();
        //            Global.Demo = true;
        //            return;
        //        }
        //    }
        //    if (iofs.CanRead == false)
        //    {
        //        Global.Demo = true;
        //        return;
        //    }
        //    int i = 0;
        //    int iCr = 0;
        //    int iLf = 0;
        //    string sCustomerID = "";
        //    string sRegistered = "";
        //    string sRegKey = "";
        //    byte[] ba = new byte[0];
        //    do
        //    {
        //        i = iofs.ReadByte();
        //        if (i == 13)
        //        {
        //            iCr = i;
        //        }

        //        if ((iCr == 13) && (i == 10))
        //        {
        //            iLf = 10;
        //        }

        //        if ((i != 13) && (i != 10) && (i != -1))
        //        {
        //            byte[] ba2 = new byte[ba.Length + 1];
        //            for (int j = 0; j < ba.Length; j++)
        //            {
        //                ba2[j] = ba[j];
        //            }
        //            ba2[ba2.Length - 1] = (byte)i;
        //            ba = new byte[ba2.Length];
        //            for (int j = 0; j < ba2.Length; j++)
        //            {
        //                ba[j] = ba2[j];
        //            }
        //        }

        //        if (i == -1)
        //        {
        //            iCr = 13;
        //            iLf = 10;
        //        }

        //        if ((iCr == 13) && (iLf == 10))
        //        {
        //            iCr = 0;
        //            iLf = 0;
        //            if (sCustomerID.Length == 0)
        //            {
        //                sCustomerID = System.Text.ASCIIEncoding.ASCII.GetString(ba);
        //                ba = new byte[0];
        //            }
        //            else
        //            {
        //                if (sRegistered.Length == 0)
        //                {
        //                    sRegistered = System.Text.ASCIIEncoding.ASCII.GetString(ba);
        //                    ba = new byte[0];
        //                }
        //                else
        //                {
        //                    if (sRegKey.Length == 0)
        //                    {
        //                        sRegKey = System.Text.ASCIIEncoding.ASCII.GetString(ba);
        //                        ba = new byte[0];
        //                        break;
        //                    }
        //                }
        //            }
        //        }
        //    } while (i != -1);

        //    if (sCustomerID.Length == 0)
        //    {
        //        if (iofs.CanWrite == true)
        //        {
        //            // File not present or empty
        //            string sNow = System.DateTime.Now.ToString();
        //            Global.DateInstalled = Convert.ToDateTime(sNow);
        //            string sNowEnc = Conversion.Encrypt(ref sNow);
        //            byte[] bOut = System.Text.ASCIIEncoding.ASCII.GetBytes(sNowEnc);
        //            iofs.Write(bOut, 0, bOut.Length);
        //        }
        //        else
        //        {
        //            Global.Demo = true;
        //        }
        //    }

        //    if ((sCustomerID.Length != 0) && (sRegistered.Length == 0))
        //    {
        //        // File present, should have a valid date/time encrypted value
        //        string sInstallDate = Conversion.Decrypt(ref sCustomerID);
        //        try
        //        {
        //            Global.DateInstalled = System.Convert.ToDateTime(sInstallDate);
        //            if (Global.DateInstalled <= System.DateTime.Now.AddDays(-Global.Days))
        //            {
        //                Global.Expired = true;
        //            }
        //            else
        //            {
        //                Global.Expired = false;
        //            }
        //        }
        //        catch
        //        {
        //            Global.DateInstalled = System.DateTime.Now.AddDays(-Global.Days);
        //            Global.Expired = true;
        //        }
        //        sCustomerID = "";
        //    }

        //    if ((sCustomerID.Length == 0) || (sRegistered.Length == 0) || (sRegKey.Length == 0))
        //    {
        //        Global.Demo = true;
        //    }
        //    else
        //    {
        //        string[] saCustomerID = sCustomerID.Split(new char[] { ':' });
        //        string[] saRegistered = sRegistered.Split(new char[] { ':' });
        //        string[] saRegKey = sRegKey.Split(new char[] { ':' });
        //        if ((saCustomerID.Length == 2) && (Conversion.Encrypt(ref saCustomerID[0]) != saCustomerID[1]))
        //        {
        //            Global.Demo = true;
        //        }
        //        else
        //        {
        //            if ((saRegistered.Length == 2) && (Conversion.Encrypt(ref saRegistered[0]) != saRegistered[1]))
        //            {
        //                Global.Demo = true;
        //            }
        //            else
        //            {
        //                if ((saRegKey.Length == 2) && (Conversion.Encrypt(ref saRegKey[0]) != saRegKey[1]))
        //                {
        //                    Global.Demo = true;
        //                }
        //                else
        //                {
        //                    Global.Demo = false;
        //                }
        //            }
        //        }
        //    }

        //    iofs.Close();
        //    iofs = null;
        //}

        /// <summary>
        /// Determins if the input string can be interpreted as a valid number.
        /// </summary>
        /// <param name="s">The string to test</param>
        /// <returns>Returns true if the string can be interpreted as a valid number</returns>
        public static bool IsNumeric(string s)
        {
            double d;

            return double.TryParse(s, out d);
        }

        /// <summary>
        /// Determins if the input string can be interpreted as a valid date/time.
        /// </summary>
        /// <param name="s">The string to test</param>
        /// <returns>Returns true if the string can be interpreted as a valid date/time</returns>
        public static bool IsDateTime(string s)
        {
            DateTime dt;

            return DateTime.TryParse(s, out dt);
        }

        /// <summary>
        /// Find the zero-based index of a given value in a given array.
        /// </summary>
        /// <param name="sa">The array of elements to search</param>
        /// <param name="sVal">The value being searched for</param>
        /// <returns>The zero-based ordinal location of the string being searched for. Returns -1 if not found.</returns>
        public static int arrayIndexOf(string[] sa, string sVal)
        {
            int iRet = -1; // Default to "not found"

            // Loop through the array
            for (int i = sa.GetLowerBound(0); i <= sa.GetUpperBound(0); i++)
            {
                // Check if the current array element matches what's being sought
                if (sa[i] == sVal)
                {
                    // Return the zero-based index
                    iRet = i;
                    // Stop searching the array
                    break;
                }
            }

            // Return the findings
            return iRet;
        }

        public static bool SendMail(string sFrom, string sTo, string sCC, string sBCC, string sSubject, string sBody)
        {
            bool bRet = false;

            SmtpClient client = new SmtpClient();

            using (MailMessage mail = new MailMessage(sFrom, sTo, sSubject, sBody))
            {
                try
                {
                    mail.IsBodyHtml = false;

                    if (sCC.Length > 0)
                    {
                        mail.CC.Add(sCC);
                    }

                    if (sBCC.Length > 0)
                    {
                        mail.Bcc.Add(sBCC);
                    }

                    client.Send(mail);

                    bRet = true;
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }

            return bRet;
        }

        public static bool LogError(string sErr, string sMapPath)
        {
            string s = "";
            return LogError(sErr, sMapPath, ref s);
        }

        public static bool LogError(string sErr, string sMapPath, ref string sMessage)
        {
            System.IO.FileStream iofs = null;
            bool bRet = false;

            string sErr2 = sErr;
            sMessage = Conversion.Encrypt(ref sErr2);

            try
            {
                string sPath = sMapPath;
                if (sPath.LastIndexOf("\\") != (sPath.Length - 1))
                {
                    sPath += "\\";
                }
                if (bLogErrorDetails == true)
                {
                    if (bEncryptErrorLogEntries == true)
                    {
                        sErr = Conversion.Encrypt(ref sErr);
                    }
                }
                iofs = new System.IO.FileStream(sPath + "rt\\error.asax", System.IO.FileMode.Append, System.IO.FileAccess.Write);
                byte[] baErr = System.Text.ASCIIEncoding.ASCII.GetBytes("---" + System.DateTime.Now.ToString() + "---\r\n" + sErr + "\r\n---End Exception---\r\n");
                iofs.Write(baErr, 0, baErr.Length);
                iofs.Close();
                iofs = null;
                bRet = true;
            }
            catch
            {
                bRet = false;
            }
            if (iofs != null)
            {
                iofs.Close();
                iofs = null;
            }

            return bRet;
        }

        //private void Global_Error(object sender, System.EventArgs e)
        //{
        //    System.Exception ex = Server.GetLastError();
        //    if (ex != null)
        //    {
        //        string sView = "";
        //        string[] saSelCols = new string[0];
        //        string[] saGroupCols = new string[0];
        //        string[] saSumCols = new string[0];
        //        string[] saAvgCols = new string[0];
        //        string[] saMaxCols = new string[0];
        //        string[] saMinCols = new string[0];
        //        string[] saCountCols = new string[0];
        //        string[] saNumFils = new string[0];
        //        string[] saDTFils = new string[0];
        //        string[] saStrFils = new string[0];
        //        string[] saBoolFils = new string[0];

        //        object obj = (object)Context.Handler;
        //        if (obj.GetType().GetProperty("sView") != null)
        //        {
        //            sView = (string)obj.GetType().GetProperty("sView").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saSelectedColumns") != null)
        //        {
        //            saSelCols = (string[])obj.GetType().GetProperty("saSelectedColumns").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saGroupColumns") != null)
        //        {
        //            saGroupCols = (string[])obj.GetType().GetProperty("saGroupColumns").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saSum") != null)
        //        {
        //            saSumCols = (string[])obj.GetType().GetProperty("saSum").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saAvg") != null)
        //        {
        //            saAvgCols = (string[])obj.GetType().GetProperty("saAvg").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saMax") != null)
        //        {
        //            saMaxCols = (string[])obj.GetType().GetProperty("saMax").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saMin") != null)
        //        {
        //            saMinCols = (string[])obj.GetType().GetProperty("saMin").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saCount") != null)
        //        {
        //            saCountCols = (string[])obj.GetType().GetProperty("saCount").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saNumericFilters") != null)
        //        {
        //            saNumFils = (string[])obj.GetType().GetProperty("saNumericFilters").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saDateTimeFilters") != null)
        //        {
        //            saDTFils = (string[])obj.GetType().GetProperty("saDateTimeFilters").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saStringFilters") != null)
        //        {
        //            saStrFils = (string[])obj.GetType().GetProperty("saStringFilters").GetValue(obj, null);
        //        }
        //        if (obj.GetType().GetProperty("saBooleanFilters") != null)
        //        {
        //            saBoolFils = (string[])obj.GetType().GetProperty("saBooleanFilters").GetValue(obj, null);
        //        }

        //        string sErr = ex.ToString();
        //        sErr += "\r\n\r\n---Class Properties---";
        //        if (bLogErrorDetails == true)
        //        {
        //            sErr += "\r\n\t[sConnectionString]=[" + Session["sConnectionString"] + "]";
        //        }
        //        sErr += "\r\n\t[sView]=[" + sView + "]";
        //        sErr += "\r\n\t[saSelCols]=[" + String.Join(", ", saSelCols) + "]";
        //        sErr += "\r\n\t[saGroupCols]=[" + String.Join(", ", saGroupCols) + "]";
        //        sErr += "\r\n\t[saSumCols]=[" + String.Join(", ", saSumCols) + "]";
        //        sErr += "\r\n\t[saAvgCols]=[" + String.Join(", ", saAvgCols) + "]";
        //        sErr += "\r\n\t[saMaxCols]=[" + String.Join(", ", saMaxCols) + "]";
        //        sErr += "\r\n\t[saMinCols]=[" + String.Join(", ", saMinCols) + "]";
        //        sErr += "\r\n\t[saCountCols]=[" + String.Join(", ", saCountCols) + "]";
        //        sErr += "\r\n\t[saNumFils]=[" + String.Join(", ", saNumFils) + "]";
        //        sErr += "\r\n\t[saDTFils]=[" + String.Join(", ", saDTFils) + "]";
        //        sErr += "\r\n\t[saStrFils]=[" + String.Join(", ", saStrFils) + "]";
        //        sErr += "\r\n\t[saBoolFils]=[" + String.Join(", ", saBoolFils) + "]";
        //        sErr += "\r\n\r\n---Last " + iMaxHistory.ToString() + " Forms---\r\n" + history.GetHistory("\r\n");
        //        Session.Add("ex", sErr);
        //        Server.ClearError();
        //        Server.Transfer("error.aspx");
        //    }
        //}

        //private void Global_BeginRequest(object sender, System.EventArgs e)
        //{
        //    history.AddHistory(Request.Url.ToString(), Request.Form, bLogErrorDetails);
        //}
    }

    public class FormHistory
    {
        private string[] sLastXForms;

        public string this[int index]
        {
            get
            {
                string sRet = "";
                if ((index >= sLastXForms.GetLowerBound(0)) & (index <= sLastXForms.GetUpperBound(0)))
                {
                    sRet = sLastXForms[index];
                }
                return sRet;
            }
            set
            {
                if ((index >= sLastXForms.GetLowerBound(0)) & (index <= sLastXForms.GetUpperBound(0)))
                {
                    sLastXForms[index] = value;
                }
            }
        }

        public string[] HistoryItems
        {
            get
            {
                int i;
                for (i = 0; i < sLastXForms.Length; i++)
                {
                    if ((sLastXForms[i] == null) || (sLastXForms[i].Length == 0))
                    {
                        break;
                    }
                }
                string[] saRet = new string[i];
                for (i = 0; i < saRet.Length; i++)
                {
                    saRet[i] = sLastXForms[i];
                }
                return saRet;
            }
        }

        public void AddHistory(string sFormName, System.Collections.Specialized.NameValueCollection form, bool bRecordDetails)
        {
            for (int i = this.MaxSize; i > 0; i--)
            {
                this[i] = this[i - 1];
            }

            string[] saRet = new string[0];
            if (bRecordDetails == true)
            {
                saRet = new string[form.Count];
                for (int i = 0; i < form.Count; i++)
                {
                    saRet[i] = "[" + form.Keys[i] + "]=[" + form[i] + "]";
                }
            }

            if (saRet.Length == 0)
            {
                if (bRecordDetails == true)
                {
                    this[0] = sFormName + "\r\n\t" + "[null]";
                }
                else
                {
                    this[0] = sFormName;
                }
            }
            else
            {
                if (bRecordDetails == true)
                {
                    this[0] = sFormName + "\r\n\t" + String.Join("\r\n\t", saRet);
                }
                else
                {
                    this[0] = sFormName;
                }
            }

            return;
        }

        public string GetHistory(string sDelimiter)
        {
            int i;
            for (i = 0; i < sLastXForms.Length; i++)
            {
                if ((sLastXForms[i] == null) || (sLastXForms[i].Length == 0))
                {
                    break;
                }
            }
            string[] saRet = new string[i];
            for (i = 0; i < saRet.Length; i++)
            {
                saRet[i] = sLastXForms[i];
            }
            return String.Join(sDelimiter, saRet);
        }

        public int MaxSize
        {
            get
            {
                return sLastXForms.Length;
            }
        }

        public FormHistory(int iMaxSize)
        {
            sLastXForms = new string[iMaxSize];
        }
    }
}